package com.one.common.manager.imageupload;

import android.content.Context;

import com.one.common.common.system.SystemModel;
import com.one.common.common.system.model.response.QiNiuTokenResponse;
import com.one.common.model.http.callback.ObserverOnNextListener;
import com.one.common.utils.Logger;
import com.one.common.utils.MD5;
import com.one.common.utils.StringUtils;
import com.one.common.utils.Toaster;
import com.one.common.utils.list.ListUtils;
import com.one.common.view.base.BaseActivity;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author：zhulunjun
 * Time：2017/9/25
 * description：七牛上传文件处理
 */

public class QINiuUploader implements IUploader {
    private static UploadManager mUploadManager;

    private static final String IMG_DIR = "images/";// images/

    /**
     * 多张图片
     */
    private int multipleSize = 0;
    private int multipleProgress = 0;
//    private ProgressListener progressListener;

    private SystemModel systemModel;
    public static final String TYPE_USER_HEAD = "1"; // 图片类型，用户头像
    private Context mContext;

    public QINiuUploader(Context context) {
        mContext = context;
        if (mUploadManager == null) {
            initUploader();
        }
        if(systemModel == null){
            systemModel = new SystemModel((BaseActivity) mContext);

        }
    }

    @Override
    public void initUploader() {
        Configuration config = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(30)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
//                .recorder(recorder)           // recorder分片上传时，已上传片记录器。默认null
//                .recorder(recorder, keyGen)   // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(FixedZone.zone0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        // 重用uploadManager。一般地，只需要创建一个uploadManager对象
        mUploadManager = new UploadManager();
    }

    @Override
    public void uploadSingle(File file, String type, UploadOptions option, ProgressListener progressHandler) {
        if (file != null && file.length() > 0) {
            Logger.d("上传图片 s " + file.length());
            String fileName = getImageName(file);
            uploadFile(file, type, fileName, option, progressHandler);
        } else {
            Logger.d("上传图片 e " + file.length());
        }
    }


    public void uploadSingle(String from, File file, String type, UploadOptions option, ProgressListener progressHandler) {
        if (file != null && file.length() > 0) {
            Logger.d("上传图片 s " + file.length());
            String fileName = getImageName(file);
            uploadFileByModifyPhone(file, type, fileName, option, progressHandler);
        } else {
            Logger.d("上传图片 e " + file.length());
        }
    }


    @Override
    public void uploadMultiple(List<File> files, String type, final ProgressListener progressHandler) {
        if (ListUtils.isNotEmpty(getNotNullFiles(files))) {
            multipleSize = files.size();
//            if (progressHandler != null) {
//                progressListener = progressHandler;
//            }
            for (File file : files) {
                if (StringUtils.isNotBlank(type)) {
                    uploadSingle(file, type);
                } else {
                    uploadSingle(file);
                }
            }
        } else {
            if (progressHandler != null) {
                progressHandler.progress("", 1, "");
            }
        }
    }

    private List<File> getNotNullFiles(List<File> files) {
        List<File> result = new ArrayList<>();
        for (File file : files) {
            if (file.exists() && file.length() > 0) {
                result.add(file);
            }
        }
        return result;
    }

    @Override
    public void uploadMultiple(List<File> files, String type) {
        uploadMultiple(files, type, null);
    }

    @Override
    public void uploadMultiple(List<File> files) {
        uploadMultiple(files, null, null);
    }

    /**
     * 上传图片
     * 获取token
     * 再上传
     */
    public void uploadFile(final File file, String type, final String fileName, final UploadOptions option, final ProgressListener progressListener) {
        Logger.d("上传图片 " + file.length()+" "+fileName);
        synchronized (this) {
            systemModel.getQiNiuToken(type, new ObserverOnNextListener<QiNiuTokenResponse>() {
                @Override
                public void onNext(QiNiuTokenResponse tokenBean) {
                    Logger.d("上传图片 token ");
                    if (tokenBean != null && StringUtils.isNotBlank(tokenBean.getToken())) {
                        mUploadManager.put(file, fileName, tokenBean.getToken(), (key, info, response) -> {
                            if (info.isOK()) {
                                // 上传多个文件逻辑
                                if (multipleSize > 0) {
                                    multipleProgress++;
                                    progressListener.progress(key, multipleProgress / multipleSize, type);
                                    if (multipleProgress == multipleSize) {
                                        multipleSize = 0;
                                    }
                                }
                                Logger.d("上传图片", "图片地址： " + key);
                            } else {
                                Logger.d("上传图片", "上传失败" + info.toString() + " token " + tokenBean.getToken());
                                if (progressListener != null) {
                                    progressListener.progress("", -1, type);
                                }
                            }
                        }, option);
                    } else {
                        Logger.d("上传图片 token null");
                        if (progressListener != null) {
                            progressListener.progress("", -1, type);
                        }
                    }
                }

                @Override
                public void onError(String errorCode, String msg) {
                    Toaster.showLongToast(msg);
                    Logger.d("上传图片 errorCode " + errorCode + " " + msg);
                    if (progressListener != null) {
                        progressListener.progress("", -1, type);
                    }
                    if (errorCode.equals("000")) {
                        systemModel.getQiNiuToken(type, new ObserverOnNextListener<QiNiuTokenResponse>() {
                            @Override
                            public void onNext(QiNiuTokenResponse qiNiuTokenResponse) {
                                Logger.d("上传图片 token2 " + qiNiuTokenResponse.toString());
                            }

                            @Override
                            public void onError(String errorCode, String msg) {
                                Logger.d("上传图片 errorCode2 " + errorCode + " " + msg);
                            }
                        });

                    }
                }
            });
            Logger.d("上传图片 jie结束了");
        }
    }

    /**
     * 上传图片 专供 登录页获取token
     * 获取token
     * 再上传
     */
    public void uploadFileByModifyPhone(final File file, String type, final String fileName, final UploadOptions option, final ProgressListener progressListener) {
        synchronized (this) {
            systemModel.getQiNiuTokenModifyMobile(type, new ObserverOnNextListener<QiNiuTokenResponse>() {
                @Override
                public void onNext(QiNiuTokenResponse tokenBean) {
                    Logger.d("上传图片 token ");
                    if (tokenBean != null && StringUtils.isNotBlank(tokenBean.getToken())) {
                        mUploadManager.put(file, fileName, tokenBean.getToken(), (key, info, response) -> {
                            if (info.isOK()) {
                                // 上传多个文件逻辑
                                if (multipleSize > 0) {
                                    multipleProgress++;
                                    progressListener.progress(key, multipleProgress / multipleSize, type);
                                    if (multipleProgress == multipleSize) {
                                        multipleSize = 0;
                                    }
                                }
                                Logger.d("上传图片", "图片地址： " + key);
                            } else {
                                Logger.d("上传图片", "上传失败" + info.toString() + " token " + tokenBean.getToken());
                                if (progressListener != null) {
                                    progressListener.progress("", -1, type);
                                }
                            }
                        }, option);
                    } else {
                        Logger.d("上传图片 token null");
                        if (progressListener != null) {
                            progressListener.progress("", -1, type);
                        }
                    }
                }

                @Override
                public void onError(String errorCode, String msg) {
                    Toaster.showLongToast(msg);
                    Logger.d("上传图片 errorCode " + errorCode + " " + msg);
                    if (progressListener != null) {
                        progressListener.progress("", -1, type);
                    }
                    if (errorCode.equals("000")) {
                        systemModel.getQiNiuToken(type, new ObserverOnNextListener<QiNiuTokenResponse>() {
                            @Override
                            public void onNext(QiNiuTokenResponse qiNiuTokenResponse) {
                                Logger.d("上传图片 token2 " + qiNiuTokenResponse.toString());
                            }

                            @Override
                            public void onError(String errorCode, String msg) {
                                Logger.d("上传图片 errorCode2 " + errorCode + " " + msg);
                            }
                        });

                    }
                }
            });
            Logger.d("上传图片 jie结束了");
        }
    }


    /**
     * 上传图片
     * 带map
     */
    public void uploadSingle(File file, String type) {
        Logger.d("上传图片 22" + file.length());
        uploadSingle(file, type, new UploadOptions(getUploadParamsMap(type), null, false, new UpProgressHandler() {
            @Override
            public void progress(String key, double percent) {
                // 上传进度
                Logger.d("上传图片", "进度 " + percent);
            }
        }, new UpCancellationSignal() {
            @Override
            public boolean isCancelled() {
                return false;
            }
        }), null);
    }

    /**
     * 上传图片
     * 带map， 和 上传进度监听
     * modify : whc
     */
    public void uploadSingle(File file, final String type, final ProgressListener progressHandler, UpCancellationSignal cancellationSignal) {
//        this.progressListener = progressHandler;
        synchronized (this) {
            uploadSingle(file, type, new UploadOptions(null, null, false, (key, percent) -> {
                Logger.e("上传图片", " " + key + " " + percent);
                if (progressHandler != null) {
                    progressHandler.progress(key, percent, type);
                }
            }, cancellationSignal), progressHandler);
        }
    }


    public void uploadSingleModifyPhone(String fromLoginModifyPhone, File file, final String type, final ProgressListener progressHandler, UpCancellationSignal cancellationSignal) {
        synchronized (this) {
            uploadSingle(fromLoginModifyPhone, file, type, new UploadOptions(null, null, false, (key, percent) -> {
                Logger.e("上传图片", " " + key + " " + percent);
                if (progressHandler != null) {
                    progressHandler.progress(key, percent, type);
                }
            }, cancellationSignal), progressHandler);
        }
    }



    public void uploadSingle(File file) {
        uploadSingle(file, "", new UploadOptions(null, null, false, new UpProgressHandler() {
            @Override
            public void progress(String key, double percent) {
                Logger.e("上传图片", " " + key + " " + percent);
            }
        },
                () -> false), null);
    }

    /**
     * 上传图片需要上传的参数
     */
    public Map<String, String> getUploadParamsMap(String type) {
        Map<String, String> map = new HashMap<>();

        return map;
    }

    /**
     * 设置文件名称
     */
    private String getImageName(File file) {
        return IMG_DIR + MD5.getFileMD5(file) + ".jpg";
    }


}
